#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
const int N = 1e5+10;
int a[N];

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int t; cin >> t;
	while (t--) {
		int n, x; cin >> n >> x;
		memset(a, 0, sizeof a);
		a[0] = 1;
		int p = 1, jw = 0;
		for (int i = 2; i <= n; i++) {
			jw = 0;
			for (int j = 0; j < p; j++) {
				a[j] = a[j] * i + jw;
				jw = a[j] / 10;
				a[j] %= 10;
			}
			while (jw > 0) {
				a[p] = jw % 10;
				p++;
				jw /= 10;
			}
			
		}
		int ans = 0;
		for (int i = 0; i < p; i++) {
			 if (a[i] == x) ans++;
		}
		cout << ans << endl;
	}
	return 0;
}